<template>
    <div class="div">
        <div class="text-xl font-bold mb-16px">
            会员卡权益设置
        </div>
        <div class="px-16px">
            <draggable v-model="rightsList" item-key="id" @end="onDragend">
                <template #item="{ element, index }">
                    <div>
                        <!-- <template v-for="(i, index) in rightsList" :key="i.id"> -->
                        <rightsSettingItem :ref="(el: refItem) => setRefMap(el, index)" :title="`会员权益${index + 1}`"
                            :form-data="element" v-model:value="rightsFormValue[index]" @delete="onDelete(index)"
                            @value-change="handleValueChange" />
                        <!-- </template> -->
                    </div>
                </template>
            </draggable>
        </div>
        <div class="px-16px sticky bottom-0 py-20px bg-white box-border">
            <el-button type="primary" plain class="w-full !border-dashed text-primary" icon="Plus"
                @click="onAdd">新增会员权益</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { AnyObject } from '@/api/type'
import type { FormDataDto } from '@/components/form-component/type'
import { getOptionsFromEnum, RightsTypeEnum, MemberUnitEnum, MemberProductEnum, MemberUseTimeModeEnum, MemberUseScopeEnum, MemberGetModeEnum, MemberUseLimitEnum, MemberGetPeriodEnum, MemberDistributeModeEnum } from '@/utils/enum'
import rightsSettingItem from './rightsSettingItem.vue'
import type { ComponentPublicInstance } from 'vue'
import { createFormValue, wait } from '@/utils/utils'
import { debounce, cloneDeep } from 'lodash'
import draggable from 'vuedraggable'

type refItem = Element | ComponentPublicInstance | null

const refMap: Record<string, refItem> = {}

/**
 * @descrption 表单数据
 */
const initFormData = () => {
    const formData = ref<FormDataDto>({
        id: new Date().getTime(),
        list: {
            rightsType: {
                label: '权益类型',
                prop: 'rightsType',
                type: 'select',
                defaultValue: 1,
                required: true,
                options: getOptionsFromEnum(RightsTypeEnum),
                extra: {
                    clearable: false
                },
                callbacks: {
                    handleChange: (val) => {
                        const rightsType1 = ['logo', 'amount', 'isCheck']
                        const rightsType4 = ['useTimeMode', 'useScope', 'money', 'useLimit', 'getMode', 'couponAmount', 'limitUse', 'distributeMode']
                        rightsType1.forEach(i => {
                            formData.value.list[i].hide = val !== 1
                        })
                        rightsType4.forEach(i => {
                            formData.value.list[i].hide = val !== 2
                        })
                    }
                }
            },
            rightsName: {
                label: '权益名称',
                prop: 'name',
                type: 'input',
                required: true,
                extra: {
                    maxlength: 10,
                    showWordLimit: true
                }
            },
            introduce: {
                label: '权益介绍',
                prop: 'introduce',
                type: 'textarea',
                required: true,
                placeholder: '最多输入2条，用‘#’键隔开',
                extra: {
                    maxlength: 28,
                    showWordLimit: true,
                },
                callbacks: {
                    handleInput: (val) => {
                        // const rights1 = ['uploadImage', 'amount', 'isCheck']
                    }
                }
            },
            isCheck: {
                label: '是否核销',
                prop: 'isWriteOff',
                type: 'radioGroup',
                required: true,
                options: [
                    {
                        label: '是',
                        value: 1
                    },
                    {
                        label: '否',
                        value: 0
                    }
                ],
                callbacks: {
                    handleChange: (val) => {
                        const props = ['useRule', 'otherRule']
                        props.forEach((i: string) => {
                            formData.value.list[i].hide = !val
                        })
                    }
                }
            },
            productId: {
                label: '选择产品',
                prop: 'productType',
                type: 'select',
                required: true,
                multiple: true,
                callbacks: {
                    handleFocus: () => {
                        formData.value.list.productId.options = getOptionsFromEnum(MemberProductEnum)
                    }
                }
                // options: getOptionsFromEnum(MemberProductEnum),
            },
            logo: {
                label: '上传图片',
                prop: 'fileUrl',
                type: 'uploadImage',
                required: true,
                defaultValue: [],
                extra: {
                    limitSize: 1,
                    withBase64Head: true,
                    hint: 'png、gif格式，小于1M',
                }
            },
            amount: {
                label: '限领数量',
                prop: 'num',
                type: 'inputGroup',
                required: true,
                extra: {
                    append: {
                        label: '',
                        prop: 'amountUnit',
                        type: 'select',
                        required: true,
                        options: getOptionsFromEnum(MemberUnitEnum),
                        extra: {
                            clearable: false
                        }
                    }
                }
            },
            // {
            //     label: '会员有效期',
            //     prop: 'validDate',
            //     type: 'input',
            //     inputType: 'number',
            //     required: true,
            //     extra: {
            //         suffix: '个月'
            //     }
            // },
            // {
            //     label: '划线价格',
            //     prop: 'showPrice',
            //     type: 'input',
            //     inputType: 'number',
            //     required: false,
            //     extra: {
            //         min: 0
            //     }
            // },
            useRule: {
                label: '使用规则',
                prop: 'useRule',
                type: 'input',
                required: false,
                hide: true,
                // extra: {
                //     maxlength: 10,
                //     showWordLimit: true
                // }
            },
            otherRule: {
                label: '其他规则',
                prop: 'otherRule',
                type: 'input',
                required: false,
                extra: {
                    maxlength: 100,
                    showWordLimit: true,
                },
                hide: true
            },
            useTimeMode: {
                label: '使用时间模式',
                prop: 'timeModel',
                type: 'select',
                required: true,
                options: getOptionsFromEnum(MemberUseTimeModeEnum),
                hide: true,
                callbacks: {
                    handleChange: (val) => {

                        formData.value.list.startTime.hide = val !== 0
                        formData.value.list.endTime.hide = val !== 0

                        formData.value.list.limitTime.hide = val !== 1
                    }
                }
            },
            startTime: {
                label: '开始时间',
                prop: 'startTime',
                type: 'date',
                required: true,
                hide: true,
                extra: {
                    class: 'width-full'
                },
                callbacks: {
                    handleChange: (val) => {
                        console.log(111, val)
                    }
                }
            },
            endTime: {
                label: '结束时间',
                prop: 'endTime',
                type: 'date',
                required: true,
                hide: true,
                extra: {
                    class: 'width-full'
                },
                callbacks: {
                    handleChange: (val) => {
                        console.log(222, val)
                    }
                }
            },
            limitTime: {
                label: '领后限时',
                prop: 'limitTime',
                type: 'input',
                inputType: 'number',
                required: true,
                extra: {
                    suffix: '天'
                },
                hide: true
            },
            useScope: {
                label: '使用范围',
                prop: 'useScope',
                type: 'checkboxGroup',
                required: true,
                options: getOptionsFromEnum(MemberUseScopeEnum),
                hide: true,
                extra: {
                    class: 'round',
                },
                callbacks: {
                    handleChange: (val) => {
                        console.log(111, val)
                    }
                }
            },
            money: {
                label: '金额',
                prop: 'amount',
                type: 'input',
                inputType: 'number',
                required: true,
                extra: {
                    suffix: ''
                },
                hide: true
            },
            useLimit: {
                label: '使用门槛',
                prop: 'useLimit',
                type: 'radioGroup',
                required: true,
                options: getOptionsFromEnum(MemberUseLimitEnum),
                hide: true,
                callbacks: {
                    handleChange: (val) => {
                        console.log(333, val)
                        formData.value.list.limitMoney.hide = val !== 1
                    }
                }
            },
            limitMoney: {
                label: '门槛金额',
                prop: 'basicsAmount',
                type: 'input',
                inputType: 'number',
                required: true,
                hide: true
            },
            getMode: {
                label: '领取模式',
                prop: 'getMode',
                type: 'radioGroup',
                required: true,
                options: getOptionsFromEnum(MemberGetModeEnum),
                hide: true,
                callbacks: {
                    handleChange: (val) => {
                        console.log(111, val)
                        formData.value.list.getPeriod.hide = val !== 2
                    }
                }
            },
            getPeriod: {
                label: '领取周期',
                prop: 'receiveModel',
                type: 'select',
                required: true,
                options: getOptionsFromEnum(MemberGetPeriodEnum),
                hide: true
            },
            couponAmount: {
                label: '数量',
                prop: 'num',
                type: 'input',
                inputType: 'number',
                required: true,
                extra: {
                    suffix: '张'
                },
                hide: true
            },
            limitUse: {
                label: '限用数量',
                prop: 'limitUse',
                type: 'inputGroup',
                required: true,
                extra: {
                    append: {
                        label: '',
                        prop: 'amountUnit',
                        type: 'select',
                        required: true,
                        options: getOptionsFromEnum(MemberUnitEnum),
                        extra: {
                            clearable: false
                        }
                    }
                },
                hide: true
            },
            distributeMode: {
                label: '发放模式',
                prop: 'distributeMode',
                type: 'select',
                required: true,
                options: getOptionsFromEnum(MemberDistributeModeEnum),
                hide: true
            },
        }
    })
    return formData.value
}

const rightsList = ref<FormDataDto[]>([])
const rightsFormValue = ref<AnyObject[]>([])

/**
 * @description 设置 refMap 对象
 *
 * @param el refItem 类型的元素
 * @param index 元素的索引
 * @returns 无返回值
 */
const setRefMap = (el: refItem, index: number) => {
    if (el) {
        refMap[`form${index}`] = el
    }
    // else {
    //     if (Object.prototype.hasOwnProperty.call(refMap, `form${index}`)) {
    //         refMap[`form${index}`] = null
    //     }
    // }
}

const emits = defineEmits(['valueChanged'])

/**
 * @description 新增会员权益
 */
const onAdd = () => {
    const initForm = initFormData()
    rightsList.value.push(initForm)
    rightsFormValue.value.push(createFormValue(initForm))
    setTimeout(() => {
        (refMap[`form${rightsList.value.length - 1}`] as InstanceType<typeof rightsSettingItem>)?.setFormValue()
    }, 0)
}

/**
 * @description 获取所有表单的值
 */
const getAllValue = () => {
    const list = []
    for (const key in refMap) {
        list.push((refMap[key] as InstanceType<typeof rightsSettingItem>)?.getFormValue())
    }
    return list
}

/**
 * @description 处理值改变
 * @returns 无返回值
 */
const handleValueChange = async () => {
    await wait(0)
    const res = await Promise.all(getAllValue())
    emits('valueChanged', res)
}

/**
 * @description 创建所有表单的提交
 * @returns 无返回值
 */
const getAllValidate = () => {
    const list = []
    for (const key in refMap) {
        list.push((refMap[key] as InstanceType<typeof rightsSettingItem>)?.submit())
    }

    console.log(1111, list)
    return list
}

/**
 * @description 提交数据函数
 * @returns 返回一个Promise对象，用于异步处理提交操作
 */
const submit = async () => {
    return new Promise(async (resolve, reject) => {
        if (!Object.values(refMap).length) {
            reject(false)
        } else {
            const res = await Promise.all(getAllValidate())
            resolve(res)
        }
    })
}

/**
 * @description 删除会员权益
 * @param index 要删除的元素的索引
 */
const onDelete = (index: number) => {
    rightsList.value.splice(index, 1)
    rightsFormValue.value.splice(index, 1)
    handleValueChange()
}

/**
 * 拖拽结束后对表单数据做同步处理
 *
 * @param val 自定义事件对象
 */
const onDragend = (val: {
    oldIndex: number
    newIndex: number
}) => {
    console.log(321, val)
    console.log(777, rightsList.value)
    const { newIndex, oldIndex } = val
    const temp = cloneDeep(rightsFormValue.value)
    // console.log(6666, rightsFormValue.value)
    rightsFormValue.value[newIndex] = temp[oldIndex]
    rightsFormValue.value[oldIndex] = temp[newIndex]
    // console.log(7777, rightsFormValue.value)
}

watch(rightsList, (newval) => {
    console.log(2121, newval)
    console.log(rightsFormValue.value)
}, {
    deep: true
})

watch(() => rightsFormValue.value, debounce((newval) => {
    emits('valueChanged', newval)
}, 300), {
    deep: true
})

defineExpose({
    submit
})

</script>
<style lang="scss" scoped>
.icon-box {
    display: flex;
    width: 16px;
    height: 16px;
    justify-content: center;
    align-items: center;
}

.icon-edit {
    width: 10px;
    height: 2px;
    border-radius: 1px;
    background: #6B6B86;
    position: relative;

    &::before {
        content: '';
        position: absolute;
        left: 0;
        top: -4px;
        width: 10px;
        height: 2px;
        border-radius: 1px;
        background: #6B6B86;
    }

    &::after {
        content: '';
        position: absolute;
        left: 0;
        bottom: -4px;
        width: 10px;
        height: 2px;
        border-radius: 1px;
        background: #6B6B86;
    }
}
</style>
